﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class MaterialService : BaseService, IMaterialService
    {
        private readonly IDictItemRepository _itemRepository;
        private readonly IMaterialCategoryRepository _materialCategoryRepository;
        private readonly IMaterialGroupRepository _materialGroupRepository;
        private readonly IMaterialRepository _materialRepository;
        private readonly IUnitOfWork _unitOfWork;
        public MaterialService(IMapper mapper, IMaterialCategoryRepository _materialCategoryRepository, IMaterialRepository _materialRepository, IMaterialGroupRepository _materialGroupRepository, IDictItemRepository _itemRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            this._materialRepository = _materialRepository;
            this._materialCategoryRepository = _materialCategoryRepository;
            this._itemRepository = _itemRepository;
            this._materialGroupRepository = _materialGroupRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddMaterial(Material m, out string message)
        {
            message = string.Empty;
            var obj = _materialRepository.QueryIsEntityWhere(x => x.Code == m.Code);
            if (obj != null)
            {
                message = $"编码：{m.Code} 重复！";
                return false;
            }
            if (!string.IsNullOrEmpty(m.MaterialEPCId))
            {
                obj = _materialRepository.QueryEntityWhere(t => t.MaterialEPCId.Equals(m.MaterialEPCId));
                if (obj != null)
                {
                    message = $"编码:{obj.Name} 已绑定:{m.MaterialEPCId}，请确认！";
                    return false;
                }
            }

            if (m.UnitId == null)
            {
                message = "请选择计量单位！";
                return false;
            }
            var iobj = _itemRepository.QueryEntityById((long)m.UnitId);
            if (iobj != null && iobj.ItemName.Length > 0)
                m.UnitName = iobj.ItemName;
            if (m.MaterialCategoryId == null)
            {
                message = "请选择物料类型！";
                return false;
            }
            var mcobj = _materialCategoryRepository.QueryEntityById((long)m.MaterialCategoryId);
            if (mcobj != null && mcobj.Name.Length > 0)
                m.MaterialCategoryName = mcobj.Name;


            _materialRepository.AddEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool AddMaterialList(List<Material> list)
        {
            if (!list.Any())
            {
                return false;
            }
            _materialRepository.AddEntityList(list);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelMaterial(long mid)
        {
            var mobj = _materialRepository.QueryEntityById(mid);

            if (mobj != null)
            {
                _materialRepository.DelEntity(mobj);
            }
            return _unitOfWork.SaveChangesEntity();
        }

        public List<Material> GetAllMaterialList()
        {
            var list = _materialRepository.GetEntityAlls();
            return list.ToList();
        }

        public Material? GetMaterialById(long mid)
        {
            return _materialRepository.QueryEntityById(mid);
        }

        public List<Material> GetMaterialList(string? mname, int materialcategoryid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _materialRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(mname))
            {
                list = list.Where(x => x.Name.Contains(mname) || x.Code.Contains(mname));
            }

            if (materialcategoryid != 0)
            {
                list = list.Where(x => x.MaterialCategoryId == materialcategoryid);
            }
            var lists = _materialRepository.GetEntityAlls(list, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return lists.ToList();
        }

        public bool UpdMaterial(Material m)
        {
            var obj = _materialRepository.QueryIsEntityWhere(x => x.Id != m.Id && x.Code == m.Code);
            if (obj != null)
            {
                return false;
            }
            obj = _materialRepository.QueryIsEntityWhere(x => x.Id != m.Id && x.Code == m.MaterialEPCId);
            if (obj != null)
            {
                return false;
            }
            if (m.UnitId == null)
                return false;
            var iobj = _itemRepository.QueryEntityById((long)m.UnitId);
            if (iobj != null && iobj.ItemName.Length > 0)
                m.UnitName = iobj.ItemName;
            if (m.MaterialCategoryId == null)
                return false;
            var mcobj = _materialCategoryRepository.QueryEntityById((long)m.MaterialCategoryId);
            if (mcobj != null && mcobj.Name.Length > 0)
                m.MaterialCategoryName = mcobj.Name;

            _materialRepository.UpdEntity(m);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool EBSAddMaterialList(List<EBSMaterialDataDTO> eBSMaterialDataDTO)
        {
            // 查询数据库中所有已存在的材料代码
            var existingMaterialCodes = _materialRepository.GetAllEntityList().Select(m => m.Code).ToList();
            var existingMaterialCodesSet = new HashSet<string>(existingMaterialCodes);

            // 创建一个新的材料列表，只包含不存在的材料代码
            List<Material> materialList = new();
            foreach (var item in eBSMaterialDataDTO)
            {
                if (!existingMaterialCodesSet.Contains(item.MaterialCode))
                {
                    var material = new Material
                    {
                        Id = YitIdHelper.NextId(),
                        Code = item.MaterialCode,
                        Name = item.MaterialName,
                        UnitName = item.UnitName,
                        MaterialCategoryName = item.MaterialCategoryName,
                        CreateUserId = 0,
                        ModifyUserId = 0,
                        ModifyDate = DateTime.Now,
                        CreateDate = DateTime.Now,
                        IsDel = false
                    };
                    materialList.Add(material);
                }
            }

            // 执行批量插入操作
            _materialRepository.AddEntityList(materialList);

            // 保存更改
            return _unitOfWork.SaveChangesEntity();
        }

        public List<Material> GetMaterialsDown()
        {
            var list = _materialRepository.GetAllEntityList();
            return list;
        }
    }
}
